import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AuthService} from "../../services/auth.service";
import {AlertService} from "../../services/alert.service";
import {Router} from "@angular/router";
import {EventbusService} from "../../services/eventbus.service";
import {StorageService} from "../../services/storage.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;
  constructor(private fb: FormBuilder
    ,private authservice:AuthService
    ,private storage:StorageService
    ,private router:Router
    ,private alertservice:AlertService
    ,private eventbus:EventbusService
  ) { }

  ngOnInit(): void {

    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]]
    });
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }

    if(this.validateForm.valid){
      // @ts-ignore
      this.authservice.login(this.validateForm.get("userName").value,this.validateForm.get("password").value)
        .then((data:any)=>{
          //console.dir(data);
          if(data.msg=='ok'){
            //console.log("准备存储");
            this.storage.set("TOKEN",data.token)
              .then(()=>{

                this.eventbus.publish('LOGIN_SUCCESS');
                this.router.navigate(['/welcome']);
              })
          }
          else if(data.msg=='locked'){
            this.alertservice.showWarning('账号被锁定，请与管理员联系');
          }
          else if(data.msg=='error'){
            this.alertservice.showError('账户异常，请与管理员联系');
          }
          else if(data.msg=='errorpass') {
            this.alertservice.showWarning('用户名或是密码错误，清核实');
          }
        })
      //console.log(this.validateForm.get("userName").value);
    }
  }
}
